<template>
  <Card
    title="预览列表（拖动可以调整列宽和位置）"
    :head-style="{ textAlign: 'center', fontWeight: 'bold' }"
    :loading="loading"
  >
    <template #extra>
      <a-button size="small" type="primary" @click="handleSelectCol">选择列</a-button>
    </template>
    <div class="w-full flex">
      <draggable
        v-model="dataRef"
        :component-data="{
          type: 'transition-group',
          class: 'draggable-macro-icon-ctl-list',
        }"
        :animation="180"
        handle=".draggable-macro-icon-ctl"
        item-key="title"
        @change="handleChange"
      >
        <template #item="{ element }">
          <div
            class="mb-2 cursor-pointer relative"
            :style="{
              backgroundColor: '#c6e1f4',
              borderTop: '1px solid #97bbd4',
              borderBottom: '1px solid #97bbd4',
              borderLeft: '1px solid #97bbd4',
              textAlign: 'center',
              height: '26px',
              lineHeight: '26px',
              '-moz-user-select': 'none',
              color: '#000',
              verticalAlign: 'middle',
              overflow: 'hidden',
              width: `${element.width}px`,
            }"
          >
            <div class="h-full w-full draggable-macro-icon-ctl flex justify-center items-center">
              <span v-html="element.fieldTitle == '#' ? element.title : element.fieldTitle"></span>
            </div>

            <div class="line" @mousedown="dragLine($event, element)"></div>
          </div>
        </template>
      </draggable>
      <Modal :width="1000" v-model:visible="open" :zIndex="2001" @ok="handleSuccess" title="选择列">
        <div class="m-5 flex flex-wrap">
          <div v-for="(item, index) in columns" :key="index" class="mb-2 w-130px">
            <Checkbox
              v-model:checked="item.value"
              :getPopupContainer="(trigger) => trigger?.parentNode"
              >{{ item.title }}</Checkbox
            >
          </div>
        </div>
      </Modal>
    </div>
  </Card>
</template>
<script lang="ts" setup>
  import { ref, watch, unref, PropType } from 'vue';
  import draggable from 'vuedraggable';
  import { Checkbox, Card, Modal } from 'ant-design-vue';
  import {
    getVisualGetColsForSetup,
    getVisualSetCols,
    relateModule,
  } from '/@/api/formDesign/formDesign';
  import { getFormGetFields } from '/@/api/flowManage/flowManage';
  import { isArray } from '/@/utils/is';
  import { useRouter } from 'vue-router';

  const { currentRoute } = useRouter();
  const emit = defineEmits(['update:modelValue']);
  const props = defineProps({
    // forms: {
    //   type: String as PropType<string>,
    //   default: '',
    // },
    formCode: {
      type: String as PropType<string>,
      default: '',
    },
  });

  const loading = ref(false);

  const dataRef = ref<Recordable[]>([]);
  const handleSelectCol = () => {
    open.value = true;
    const fields = dataRef.value.map((item) => item.field);
    columns.value.forEach((item) => {
      if (fields.includes(item.name)) {
        item.value = true;
      }
    });
  };

  const columns = ref<Recordable[]>([]);
  const open = ref(false);
  const handleSuccess = () => {
    const dataList = columns.value.filter((item) => item.value);
    console.log('dataList', {
      dataList,
      dataRef: dataRef.value,
    });
    const names = dataList.map((item) => item.name);
    const fields = dataRef.value.map((item) => item.field);
    const newDataList = dataList.filter((item) => !fields.includes(item.name));
    dataRef.value = dataRef.value.filter((item) => names.includes(item.field));
    dataRef.value = [...dataRef.value, ...newDataList];
    open.value = false;
    handleChange();
  };

  const fetch = async (oldVal) => {
    console.log('props', props);

    if (!props.formCode) return;
    getFormGetFieldsData();
    loading.value = true;

    const { query } = currentRoute.value as any;
    const mainFormCode = query?.formCode;
    // 使模块相关联
    await relateModule({
      formCode: mainFormCode,
      relateCode: props.formCode,
      oldRelateCode: oldVal,
    });

    const data = await getVisualGetColsForSetup({ moduleCode: props.formCode });
    dataRef.value = data || [];
    loading.value = false;
  };

  // cols: [{"field":"store_id","width":150,"link":"#","show":true,"title":"仓库名称","fieldTitle":"#","fieldAlign":"center","name":"store_id"},{"field":"date","width":88.333333,"link":"#","show":true,"title":"出库日期","fieldTitle":"#","fieldAlign":"center","name":"date"},{"field":"ck_lx","width":150,"link":"#","show":true,"title":"出库类型","fieldTitle":"#","fieldAlign":"center","name":"ck_lx"},{"field":"ck_person","width":150,"link":"#","show":true,"title":"出库人","fieldTitle":"#","fieldAlign":"center","name":"ck_person"}]

  //获取条件映射数据
  const getFormGetFieldsData = () => {
    columns.value = [];
    try {
      // const { query } = currentRoute.value;
      if (!props.formCode) return;
      getFormGetFields({ formCode: props.formCode }).then((res) => {
        columns.value = res || [];
        columns.value.forEach((item: Recordable) => {
          item.value = false;
        });
        console.log('columns', columns.value);
      });
    } catch (err) {
      console.log('getFormGetFields', err);
    }
  };

  watch(
    () => props.formCode,
    async (newVal, oldVal) => {
      fetch(oldVal);
    },
    {
      immediate: true,
    },
  );

  const handleChange = () => {
    console.log('uui', dataRef.value);
    emit('update:modelValue', unref(dataRef));
    setCols();
  };

  const setCols = async () => {
    try {
      dataRef.value = dataRef.value.map((item) => {
        return {
          field: item.field || item.name,
          fieldAlign: 'center',
          fieldTitle: '#',
          link: '#',
          title: item.title,
          width: item.width,
          group: item.group,
          rowGroup: item.rowGroup,
        };
      });
      const params = {
        moduleCode: props.formCode,
        cols: JSON.stringify(dataRef.value),
      };
      loading.value = true;
      console.log('params', params);
      await getVisualSetCols(params);
      fetch();
    } catch (error) {
      console.log('setCols', setCols);
    } finally {
      loading.value = false;
    }
  };

  const dragLine = (event, record) => {
    let orgWidth = event.clientX - record.width;
    document.onmousemove = (e) => {
      // console.log('e', e)
      //鼠标点击拖动时
      record.width = e.clientX - orgWidth;
    }; //绑定onmouseup
    document.onmouseup = () => {
      // //松开鼠标时
      if (record.width > 300) {
        record.width = 300;
      } else if (record.width < 50) {
        record.width = 50;
      }
      handleChange();
      //解绑
      document.onmousemove = null;
      document.onmouseup = null;
    };
  };
</script>
<style scoped>
  .draggable-macro-icon-ctl-list {
    display: flex;
    flex-wrap: wrap;
  }
  .line {
    position: absolute;
    width: 20px;
    height: 100%;
    right: -1px;
    z-index: 10;
    top: 0;
    /* height: calc(100% - 130px); */
    cursor: col-resize;
    overflow: hidden;
    z-index: 4;
    user-select: none;
    &::after {
      content: '';
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      display: block;
      margin: auto;
      width: 0;
      /* border: 1px dashed #ccc; */
    }
  }
</style>
